<template>
  <el-container class="products-container">
    <el-aside width="220px" class="filter-aside">
      <el-card>
        <template #header>
          <h3>筛选与排序</h3>
        </template>
        <!-- 分类筛选 -->
        <div class="filter-group">
          <h4>商品分类</h4>
          <el-radio-group v-model="filters.category_slug" @change="handleFilterChange">
            <el-radio-button value="">全部</el-radio-button>
            <el-radio-button 
              v-for="category in categories"
              :key="category.id" 
              :value="category.slug"
            >
              {{ category.name }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 排序方式 -->
        <div class="filter-group">
          <h4>排序方式</h4>
          <el-select v-model="filters.sort_by" placeholder="选择排序字段" @change="handleSortChange">
            <el-option label="最新上架" value="created_at"></el-option>
            <el-option label="价格从低到高" value="price"></el-option>
            <el-option label="价格从高到低" value="price_desc"></el-option>
            <el-option label="名称 A-Z" value="name"></el-option>
          </el-select>
        </div>
        
        <!-- 搜索 -->
        <div class="filter-group">
          <h4>搜索商品</h4>
          <el-input 
            v-model="filters.search" 
            placeholder="输入关键词搜索"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          >
            <template #append>
              <el-button :icon="SearchIcon" @click="handleSearch" />
            </template>
          </el-input>
        </div>

      </el-card>
    </el-aside>

    <el-main>
      <el-card>
        <div v-if="loading" class="loading-spinner">
          <el-progress :percentage="50" :indeterminate="true" />
          <p>加载中...</p>
        </div>
        <div v-else-if="error" class="error-message">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
        <div v-else>
          <div v-if="products.length === 0 && !loading" class="no-products">
            <el-empty description="暂无符合条件的商品" />
          </div>
          <el-row v-else :gutter="20">
            <el-col
              v-for="product in products"
              :key="product.id"
              :xs="24" :sm="12" :md="8" :lg="6"
              class="product-col"
            >
              <el-card shadow="hover" class="product-card">
                <img 
                  :src="product.thumbnail_url || 'https://via.placeholder.com/300x200.png?text=No+Image'" 
                  class="product-image" 
                  alt="商品图片"
                  @click="goToProductDetail(product.slug)"
                />
                <div class="product-info">
                  <h3 class="product-name" @click="goToProductDetail(product.slug)">
                    {{ product.name }}
                  </h3>
                  <p class="product-price">¥ {{ product.price }}</p>
                  <el-button type="warning" plain size="small" @click="addToCart(product)">
                     <el-icon><ShoppingCart /></el-icon> 添加到购物车
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-pagination
            v-if="pagination.total_pages > 1"
            class="pagination-container"
            background
            layout="prev, pager, next, jumper, ->, total"
            :total="pagination.total"
            :page-size="pagination.limit"
            :current-page="pagination.page"
            @current-change="handlePageChange"
          />
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import productService from '../api/product.service';
import categoryService from '../api/category.service';
import cartService from '../api/cart.service';
import { ElMessage } from 'element-plus';
import { Search as SearchIcon } from '@element-plus/icons-vue'; // ShoppingCart 已全局注册

const router = useRouter();
const route = useRoute();

const products = ref([]);
const categories = ref([]);
const loading = ref(false);
const error = ref(null);

const filters = reactive({
  category_slug: route.query.category_slug || '',
  search: route.query.search || '',
  sort_by: route.query.sort_by || 'created_at',
  sort_order: route.query.sort_order || 'desc',
});

const pagination = reactive({
  page: parseInt(route.query.page) || 1,
  limit: 12, // 每页数量
  total: 0,
  total_pages: 0,
});

const fetchProducts = async () => {
  loading.value = true;
  error.value = null;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      category_slug: filters.category_slug || null,
      search: filters.search || null,
      sort_by: filters.sort_by,
      sort_order: filters.sort_order,
    };
    if (filters.sort_by === 'price_desc') {
      params.sort_by = 'price';
      params.sort_order = 'desc';
    }

    const response = await productService.getProducts(params);
    products.value = response.data;
    pagination.total = response.meta.total;
    pagination.total_pages = response.meta.last_page; // API返回的是last_page
    pagination.page = response.meta.current_page;
    pagination.limit = response.meta.per_page;

    // 更新URL查询参数，不触发导航
    router.replace({ query: { ...route.query, ...params, page: pagination.page } });

  } catch (err) {
    console.error('获取商品失败:', err);
    error.value = err.message || '获取商品数据失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const fetchCategories = async () => {
  try {
    const response = await categoryService.getCategories(); // 获取所有顶级分类
    categories.value = response.data;
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取商品分类失败');
  }
};

const handlePageChange = (newPage) => {
  pagination.page = newPage;
  fetchProducts();
};

const handleFilterChange = () => {
  pagination.page = 1; // 重置到第一页
  fetchProducts();
};

const handleSortChange = (value) => {
  if (value === 'price_desc') {
    filters.sort_by = 'price';
    filters.sort_order = 'desc';
  } else {
    filters.sort_by = value;
    filters.sort_order = (value === 'created_at') ? 'desc' : 'asc';
  }
  pagination.page = 1;
  fetchProducts();
};

const handleSearch = () => {
  pagination.page = 1;
  fetchProducts();
}

const goToProductDetail = (slug) => {
  router.push({ name: 'ProductDetail', params: { slug } });
};

const addToCart = async (product) => {
  try {
    await cartService.addItem({ product_id: product.id, quantity: 1 });
    ElMessage.success(`${product.name} 已添加到购物车`);
  } catch (err) {
    console.error('添加到购物车失败:', err);
    const errorMessage = err.message || '添加到购物车失败';
    ElMessage.error(errorMessage);
  }
};

// 监听路由查询参数变化，以便从其他地方导航过来时能正确加载数据
watch(() => route.query, (newQuery) => {
  filters.category_slug = newQuery.category_slug || '';
  filters.search = newQuery.search || '';
  filters.sort_by = newQuery.sort_by || 'created_at';
  filters.sort_order = newQuery.sort_order || 'desc';
  pagination.page = parseInt(newQuery.page) || 1;
  fetchProducts();
}, { deep: true });

onMounted(() => {
  fetchCategories(); // 先获取分类用于筛选
  fetchProducts();   // 然后获取商品
});

</script>

<style scoped>
.products-container {
  padding: 20px;
}

.filter-aside {
  margin-right: 20px;
}

.filter-group {
  margin-bottom: 20px;
}

.filter-group h4 {
  margin-bottom: 10px;
}

.el-radio-group .el-radio-button {
    margin-bottom: 5px; 
    display: block; /* 让每个按钮占据一行 */
}

.el-radio-group .el-radio-button:not(:last-child) {
    margin-right: 0; /* 移除默认右边距 */
}

.el-select {
  width: 100%;
}

.loading-spinner,
.error-message,
.no-products {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.product-col {
  margin-bottom: 20px;
}

.product-card {
  cursor: pointer;
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

.product-info {
  padding: 14px;
  text-align: left;
}

.product-name {
  font-size: 16px;
  margin: 10px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #ff4d4f;
  font-size: 18px;
  margin-bottom: 10px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}
</style> 